/**
 * 认证状态管理
 */

import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { User } from '@/types'
import {
  setToken,
  setRefreshToken,
  setUser,
  clearAuth as clearAuthStorage,
  isTokenExpired,
} from '@/utils/auth'

interface AuthState {
  // 状态
  user: User | null
  token: string | null
  isAuthenticated: boolean

  // Actions
  setAuth: (user: User, token: string, refreshToken?: string) => void
  updateUser: (user: Partial<User>) => void
  clearAuth: () => void
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      // 初始状态
      user: null,
      token: null,
      isAuthenticated: false,

      // 设置认证信息
      setAuth: (user, token, refreshToken) => {
        setToken(token)
        setUser(user)
        if (refreshToken) {
          setRefreshToken(refreshToken)
        }

        set({
          user,
          token,
          isAuthenticated: true,
        })
      },

      // 更新用户信息
      updateUser: (userData) => {
        set((state) => {
          if (!state.user) return state

          const updatedUser = { ...state.user, ...userData }
          setUser(updatedUser)

          return {
            user: updatedUser,
          }
        })
      },

      // 清除认证信息
      clearAuth: () => {
        clearAuthStorage()
        set({
          user: null,
          token: null,
          isAuthenticated: false,
        })
      },
    }),
    {
      name: 'auth-storage', // LocalStorage key
      partialize: (state) => ({
        user: state.user,
        token: state.token,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
)

// 初始化时验证认证状态
const validateAuthOnInit = () => {
  const state = useAuthStore.getState()

  if (state.isAuthenticated) {
    // 验证 token
    if (!state.token) {
      console.warn('[Auth] 无效的认证状态（无token），已清除')
      state.clearAuth()
    } else {
      try {
        if (isTokenExpired(state.token)) {
          console.warn('[Auth] Token 已过期，已清除认证状态')
          state.clearAuth()
        } else {
          console.log('[Auth] 用户已登录:', state.user?.username)
        }
      } catch (error) {
        console.error('[Auth] Token 验证失败:', error)
        state.clearAuth()
      }
    }
  } else {
    console.log('[Auth] 用户未登录')
  }
}

// 应用启动时立即执行验证
validateAuthOnInit()
